/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "common.h"
#include "verifier.h"
#include "ui.h"

#include "mincrypt/rsa.h"
#include "mincrypt/sha.h"

#include <string.h>
#include <stdio.h>
#include <errno.h>

extern RecoveryUI* ui;
extern int old_updatezip_flag;

char *known_sha1s[] = {
            "01c041ee4803755cc4bc00e108e0a613dcc782ab",
            "a23f051c805b586608ccd63d0257ad867f577bdf",
            "5acb8d649a0416ae1730e2a3b45aafb1727bb9be",
            "4bfe92f6f2bafb20979d881b773933dcc438f88b",
            "82fb1103c4e8d281e891bae12d26283332cb74ac",
            "6349f6ec3794e799b52c87eee674dc3ad2435c79",
            "dc2a66de723aa1889eaa6b7cef2fb05d8d9a7590",
            "9406448609c52c0e8109afbfb77110f838f41c4e",
            "a589842eb4ab97e45dc1d68041e77dd72a71a63c",
            "b6e27016ff3eb502c634b753427d9f179e15f2ff",
            "a6277d7ef65dda2a061aa7cd1620d82e787f9de4",
            "903f681c6c4e177007b1653128f61b19d247444f",
            "3715d801b92a5f1edbbcc819b1f57f2def1c85de",
            "a694007371fd0e11daef3a72b8fefe071ca61a28",
            "a623c066541f0ea8476e8b39ccbd4dcc7dac96ec",
            "9affed9d8ddf7e0748b4698080924f0e03aee405",
            "6514aba7766a47a8c42cd72ca015879be6480742",
            "bf7f2cfb83036679f322e3799c160ad05f8cf57d",
            "96987b650e13add4afc91da7e41c0dba3edaf389",
            "d2e24724eaf59ee97a0934a168dbee310215ef7d",
            "8b48f62a33892d9ca2cc5be5c882b795f01b557b",
            "2b77b87efddd5a0df2796632030b6a9d4f2597f0",
            "02199a977fd02748a40a9da5c3bf698fa01b5dd1",
            "7471f677c88f269711ded5994cfcfaebcaa22de4",
            "c9b2578e1164c739d121d262b50efd09d00abbd8",
            "fd174556f4ec76acc98e16c545fda954603d3f4a",
            "NULL"};


// Look for an RSA signature embedded in the .ZIP file comment given
// the path to the zip.  Verify it matches one of the given public
// keys.
//
// Return VERIFY_SUCCESS, VERIFY_FAILURE (if any error is encountered
// or no key matches the signature).

int verify_file(const char* path, const RSAPublicKey *pKeys, unsigned int numKeys) {
    ui->SetProgress(0.0);

    FILE* f = fopen(path, "rb");
    if (f == NULL) {
        LOGE("failed to open %s (%s)\n", path, strerror(errno));
        return VERIFY_FAILURE;
    }

    // An archive with a whole-file signature will end in six bytes:
    //
    //   (2-byte signature start) $ff $ff (2-byte comment size)
    //
    // (As far as the ZIP format is concerned, these are part of the
    // archive comment.)  We start by reading this footer, this tells
    // us how far back from the end we have to start reading to find
    // the whole comment.

#define FOOTER_SIZE 6

    if (fseek(f, -FOOTER_SIZE, SEEK_END) != 0) {
        LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    unsigned char footer[FOOTER_SIZE];
    if (fread(footer, 1, FOOTER_SIZE, f) != FOOTER_SIZE) {
        LOGE("failed to read footer from %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    if (footer[2] != 0xff || footer[3] != 0xff) {
        fclose(f);
        return VERIFY_FAILURE;
    }

    size_t comment_size = footer[4] + (footer[5] << 8);
    size_t signature_start = footer[0] + (footer[1] << 8);
    LOGI("comment is %d bytes; signature %d bytes from end\n",
         comment_size, signature_start);

    if (signature_start - FOOTER_SIZE < RSANUMBYTES) {
        // "signature" block isn't big enough to contain an RSA block.
        LOGE("signature is too short\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

#define EOCD_HEADER_SIZE 22

    // The end-of-central-directory record is 22 bytes plus any
    // comment length.
    size_t eocd_size = comment_size + EOCD_HEADER_SIZE;

    if (fseek(f, -eocd_size, SEEK_END) != 0) {
        LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    // Determine how much of the file is covered by the signature.
    // This is everything except the signature data and length, which
    // includes all of the EOCD except for the comment length field (2
    // bytes) and the comment data.
    size_t signed_len = ftell(f) + EOCD_HEADER_SIZE - 2;

    unsigned char* eocd = (unsigned char*)malloc(eocd_size);
    if (eocd == NULL) {
        LOGE("malloc for EOCD record failed\n");
        fclose(f);
        return VERIFY_FAILURE;
    }
    if (fread(eocd, 1, eocd_size, f) != eocd_size) {
        LOGE("failed to read eocd from %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }

    // If this is really is the EOCD record, it will begin with the
    // magic number $50 $4b $05 $06.
    if (eocd[0] != 0x50 || eocd[1] != 0x4b ||
        eocd[2] != 0x05 || eocd[3] != 0x06) {
        LOGE("signature length doesn't match EOCD marker\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

    size_t i;
    for (i = 4; i < eocd_size-3; ++i) {
        if (eocd[i  ] == 0x50 && eocd[i+1] == 0x4b &&
            eocd[i+2] == 0x05 && eocd[i+3] == 0x06) {
            // if the sequence $50 $4b $05 $06 appears anywhere after
            // the real one, minzip will find the later (wrong) one,
            // which could be exploitable.  Fail verification if
            // this sequence occurs anywhere after the real one.
            LOGE("EOCD marker occurs after start of EOCD\n");
            fclose(f);
            return VERIFY_FAILURE;
        }
    }

#define BUFFER_SIZE 4096

    SHA_CTX ctx;
    SHA_init(&ctx);
    unsigned char* buffer = (unsigned char*)malloc(BUFFER_SIZE);
    if (buffer == NULL) {
        LOGE("failed to alloc memory for sha1 buffer\n");
        fclose(f);
        return VERIFY_FAILURE;
    }

    double frac = -1.0;
    size_t so_far = 0;
    fseek(f, 0, SEEK_SET);
    while (so_far < signed_len) {
        size_t size = BUFFER_SIZE;
        if (signed_len - so_far < size) size = signed_len - so_far;
        if (fread(buffer, 1, size, f) != size) {
            LOGE("failed to read data from %s (%s)\n", path, strerror(errno));
            fclose(f);
            return VERIFY_FAILURE;
        }
        SHA_update(&ctx, buffer, size);
        so_far += size;
        double f = so_far / (double)signed_len;
        if (f > frac + 0.02 || size == so_far) {
            ui->SetProgress(f);
            frac = f;
        }
    }
    free(buffer);
    const uint8_t* sha1 = SHA_final(&ctx);
    for (i = 0; i < numKeys; ++i) {
        // The 6 bytes is the "(signature_start) $ff $ff (comment_size)" that
        // the signing tool appends after the signature itself.
        if (RSA_verify(pKeys+i, eocd + eocd_size - 6 - RSANUMBYTES,
                       RSANUMBYTES, sha1)) {
            LOGI("whole-file signature verified against key %d\n", i);
		    fclose(f);
            free(eocd);
            return VERIFY_SUCCESS;
        }
    }
    /*verify old public rom */
    char tmp_sha[42] = {0};
    char const * hex = "0123456789ABCDEF";
    for(i=0;i<20;i++)
    {
        tmp_sha[i*2] = hex[sha1[i] >> 4];
        tmp_sha[i*2 + 1] = hex[sha1[i] & 0x0f];
    }
    char **p ;
    p= known_sha1s;
    while(strcasecmp(*p,"NULL")!=0)
    {
        if(strcasecmp(*p,tmp_sha)==0)
        {
            old_updatezip_flag =1;
            fclose(f);	
            return VERIFY_SUCCESS;
        }
        p++;
    }

        /*验证过度rom*/
    if (fseek(f, -comment_size, SEEK_END) != 0) {
        LOGE("failed to seek in %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }
    unsigned char sig[1];
    if (fread(sig, 1, 1, f) != 1) {
        LOGE("failed to read footer from %s (%s)\n", path, strerror(errno));
        fclose(f);
        return VERIFY_FAILURE;
    }
    if(sig[0]==83)
    {
        fclose(f);
        return VERIFY_SUCCESS;
    }

    
    fclose(f);
    free(eocd);
    LOGE("failed to verify whole-file signature\n");
    return VERIFY_FAILURE;
}
